package mobi.pooper;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.ScaleTo;
import com.badlogic.gdx.scenes.scene2d.actions.Sequence;
import com.badlogic.gdx.scenes.scene2d.ui.Align;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.Scaling;

import static mobi.pooper.Constants.*;

public class PickableImage extends Image {

	private static final String TAG = PickableImage.class.getSimpleName();
	private Sound sound;
	
	private ClickListener clkListener = new ClickListener(){

		@Override
		public void click(Actor actor, float x, float y) {
			if(PickableImage.this.y < 200){
				PickableImage.this.x = anchorX;
				PickableImage.this.y = anchorY;
				action(Sequence.$(ScaleTo.$(3, 3, 0.5F), ScaleTo.$(1, 1, 2)));
				sound.play();
			}else{
				GameStage stage = (GameStage) getStage();
				if(rightPicture){
					stage.getPooper().showResult(Pooper.YES);
					Gdx.app.debug(TAG, "Result is YES!");
				}else{
					stage.getPooper().showResult(Pooper.NO);
					Gdx.app.debug(TAG, "Result is NO!");
				}
			}
		}
	};

	private float anchorX;
	private float anchorY;
	private boolean rightPicture;

	@Override
	public void touchDragged(float x, float y, int pointer) {
		Gdx.app.debug(TAG, "touchDragged: " + x + " " + y);
		this.x += x - width / 2;
		this.y += y - height / 2;
		super.touchDragged(x, y, pointer);
	}

	public PickableImage(Texture texture, Scaling scaling, float x, float y, String name, boolean rightPicture) {
		super(texture, scaling, Align.BOTTOM | Align.LEFT, name);
		setClickListener(clkListener);
		anchorX = x;
		anchorY = y;
		this.x = x;
		this.y = y;
		this.rightPicture = rightPicture;
		
		FileHandle soundFile = Gdx.files.internal(TASKS_PATH + "/" + name + ".mp3");
		if(soundFile.exists()){
			sound = Gdx.audio.newSound(soundFile);
		}else{
			sound = Gdx.audio.newSound(Gdx.files.internal(NO_SOUND_FILE));
		}
	}
}
